package cn.yangliu.config.custom;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.yangliu.comm.JsonResult;
import com.alibaba.fastjson.JSON;
import lombok.Cleanup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

@Component
public class AuthenticationSuccessHandler
        implements org.springframework.security.web.authentication.AuthenticationSuccessHandler, SecurityHandler {
    @Autowired
    private TokenStore tokenStore;
    @Autowired
    private TokenGenerator tokenGenerator;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        @Cleanup PrintWriter writer = response.getWriter();
        String msg = "success";
        String token = tokenGenerator.generate(authentication);
        tokenStore.store(token, authentication);
        response.setHeader(TokenAuthenticationFilter.tokenHeadName, token);
        JsonResult<Object> jsonResult = JsonResult.getInstance(HttpStatus.OK.value(), msg);
        jsonResult.setData(token);
        String json = JSON.toJSONString(jsonResult);
        writer.println(json);
    }


}
